package com.sbio.udiapp.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.sbio.udiapp.R;
import com.sbio.udiapp.ui.RawMaterialSubPackActivity;
import com.sbio.udiapp.ui.model.PrdMtrlView1;

import java.util.List;

public class RawMaterialSubPackListViewAdapter<T extends ListItemData> extends RecyclerView.Adapter<RawMaterialSubPackListViewAdapter.ViewHolder> {

    private List<T> dataList;

    private Context context;

    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public RawMaterialSubPackListViewAdapter(List<T> dataList, Context context) {
        this.dataList = dataList;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_list_view_item2, parent, false);
        return new ViewHolder(view);
    }

    //    @SuppressLint("RecyclerView")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        T data = dataList.get(position);
//        holder.bind(data, listener, position);
        int selectedPosition = ((RawMaterialSubPackActivity) context).getCurrentSelectedPosition();
        if (selectedPosition == position) {
            holder.tv.setChecked(true);
            holder.tv.setBackgroundResource(R.drawable.list_item_selector);
        } else {
            holder.tv.setChecked(false);
            holder.tv.setBackgroundResource(R.drawable.list_item_selector);
        }
        holder.tv.setText(data.getDisplayText());
        holder.tv.setOnClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onItemClick(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }


    public static class ViewHolder extends RecyclerView.ViewHolder {

        CheckedTextView tv;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tv = itemView.findViewById(R.id.tv_box_code);
        }

        // 修改 bind 方法接收 ListItemData 类型
        public void bind(PrdMtrlView1 data, OnItemClickListener listener, int position) {
            tv.setText(data.getDisplayText());
            tv.setOnClickListener(v -> listener.onItemClick(position));
        }
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

}